package com.oeandn.common.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 饮水机管理员
 */
@Slf4j
public class WebSocketSessionManager {

    public  static ConcurrentHashMap<String, WebSocketSession> sessionGroup = new ConcurrentHashMap<>();


    public static void add(WebSocketSession session) {
        // 添加 session
        sessionGroup.put(session.getId(), session);
    }


    public static WebSocketSession remove(String key) {
        // 删除 session
        return sessionGroup.remove(key);
    }
    

    public static WebSocketSession remove(WebSocketSession session) {
        // 删除 session
        return sessionGroup.remove(session.getId());
    }
    

    public static void removeAndClose(String key) {
        WebSocketSession session = remove(key);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                log.error("关闭出现异常处理",e);
            }
        }
    }
    

    public static void removeAndClose(WebSocketSession session) {
        session = remove(session);
        if (session != null) {
            try {
                // 关闭连接
                session.close();
            } catch (IOException e) {
                log.error("关闭出现异常处理",e);
            }
        }
    }
    

    public static WebSocketSession get(String key) {
        // 获得 session
        return sessionGroup.get(key);
    }
	
}

